package hu.fic.weddingstorefinder.activity;

import hu.fic.weddingstorefinder.R;
import hu.fic.weddingstorefinder.db.WeddingStoreDBAdapter;
import hu.fic.weddingstorefinder.db.table.ApplicationConf;
import hu.fic.weddingstorefinder.db.table.POI;
import hu.fic.weddingstorefinder.map.StoreItemizedOverlay;
import hu.fic.weddingstorefinder.map.StoreItemizedOverlayListener;
import hu.fic.weddingstorefinder.map.StoreOverlayItem;
import hu.fic.weddingstorefinder.parcel.StoreParcelable;
import hu.fic.weddingstorefinder.utils.Constants;
import hu.fic.weddingstorefinder.utils.UpdateHandler;
import hu.fic.weddingstorefinder.utils.UpdateHandlerListener;
import hu.fic.weddingstorefinder.utils.Utils;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.location.Location;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;

public class StoreMapActivity extends MapActivity implements UpdateHandlerListener {

	private ProgressDialog pd;
	private MapView mapView;
	private MyLocationOverlay myLocationOverlay;
	private StoreItemizedOverlay storesOverlay;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		try {
			super.onCreate(savedInstanceState);
			WeddingStoreDBAdapter.createInstance(this);
			setContentView(R.layout.mapactivity);
			ApplicationConf.initAppConf(WeddingStoreDBAdapter.getInstance().getDb(), this);
			this.checkForUpdate();
			mapView = (MapView) findViewById(R.id.mapview);
			mapView.setBuiltInZoomControls(true);
			
			
			// create an overlay that shows our current location
			myLocationOverlay = new MyLocationOverlay(this, mapView);
			
			// add this overlay to the MapView and refresh it
			mapView.getOverlays().add(myLocationOverlay);
			this.refreshPOIs();
			mapView.postInvalidate();
			
			double[] coordinatesToShow = getIntent().getDoubleArrayExtra(Constants.COORDINATES_TO_SHOW_KEY);
			if (coordinatesToShow == null || coordinatesToShow.length != 2) {
				mapView.getController().animateTo(new GeoPoint(Constants.DEFAULT_LATITUDE, Constants.DEFAULT_LONGITUDE));
				mapView.getController().setZoom(16);
			} else {
				GeoPoint pointToNavogate = new GeoPoint((int)(coordinatesToShow[1] * 1e6), (int)(coordinatesToShow[0] * 1e6));
				mapView.getController().animateTo(pointToNavogate);
				mapView.getController().setZoom(17);
			}
			
			
			//TESZT - TOROLNI
			//ApplicationConf.setLongForKey(ApplicationConf.APPCONF_KEY_LASTUPDATE_TIMESTAMP, 0);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void onDestroy() {
		WeddingStoreDBAdapter.closeDB();
		super.onDestroy();
	}

	@Override
	protected void onPause() {
		super.onPause();
		try {
			myLocationOverlay.disableMyLocation();
			ApplicationConf.saveAppConf();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		// when our activity resumes, we want to register for location updates
		myLocationOverlay.enableMyLocation();
	}

	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mapactivitymanu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == R.id.menuitem_update) {
			this.updateDB();
		} else if (item.getItemId() == R.id.menuitem_storelist) {
			Intent intent = new Intent(this, StoreListActivity.class);
			Location myLocation = myLocationOverlay.getLastFix();
			//double[]myLocationCoordninates = {myLocation.getLongitude(), myLocation.getLatitude()};
			intent.putExtra(Constants.LAST_FIX_KEY, myLocation);
			this.startActivity(intent);
		} else if (item.getItemId() == R.id.menuitem_dresslist) {
			Intent intent = new Intent(this, DressListActivity.class);
			this.startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	private void checkForUpdate() {
		UpdateHandler updateHandler = new UpdateHandler(this, this);
		updateHandler.checkForUpdate();
	}

	private void updateDB() {
		UpdateHandler updateHandler = new UpdateHandler(this, this);
		updateHandler.update();
	}

	@Override
	public void updateIsInProgress(String progressMessage) {
		if (pd == null) {
			pd = ProgressDialog.show(this, this.getString(R.string.update), progressMessage);
		} else {
			pd.setMessage(progressMessage);
		}

	}

	@Override
	public void needUpdate(boolean needUpdate) {
		if (needUpdate) {
			Utils.showDialog(getString(R.string.updates_available), getString(R.string.update_question), getString(R.string.update_now), new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// update db
					StoreMapActivity.this.updateDB();
					dialog.dismiss();
				}
			}, getString(R.string.no_thanks), null, this);
			
		}
	}

	@Override
	public void updateHandlerDone(UpdateHandler updateHandler) {
		if (pd != null) {
			pd.dismiss();
			pd = null;
		}
		Utils.showInfoDialog(null, updateHandler.getUpdateResultMessage(), getString(R.string.ok), this);
		try {
			this.refreshPOIs();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void updateHandlerFailed(UpdateHandler updateHandler) {
		
		if (pd != null) {
			pd.dismiss();
			pd = null;
		}
		if (updateHandler.getUpdateType() == Constants.UPDATE_TYPE_UPDATE) {
			Utils.showInfoDialog(getString(R.string.error), updateHandler.getErrorMessage(), getString(R.string.ok), this);
		}
		
	}
	
	public void refreshPOIs() throws Exception {
		if (storesOverlay == null) {
			storesOverlay = new StoreItemizedOverlay(this.getResources().getDrawable(R.drawable.pin), new StoreItemizedOverlayListener() {	
				@Override
				public void onTapToItem(StoreOverlayItem overlayItem) {
					
					Intent intent = new Intent(StoreMapActivity.this, StoreDetailsActivity.class);
					intent.putExtra(Constants.POI_PARCEL_KEY, overlayItem.getStoreParcelable());
					StoreMapActivity.this.startActivity(intent);
				}
			});
			mapView.getOverlays().add(storesOverlay);
		} else {
			storesOverlay.removeAll();
		}
		
		//load all pois:
		POI poi = new POI(WeddingStoreDBAdapter.getInstance().getDb(), this);
		poi.loadAll();
		while (poi.nextRow()) {
			GeoPoint point = new GeoPoint((int)(poi.getLatitude() * 1e6), (int)(poi.getLongitude() * 1e6));
			StoreParcelable soreParc = new StoreParcelable(poi);
			StoreOverlayItem poiOverlay = new StoreOverlayItem(point, poi.getPOIName(), poi.getAddress(), soreParc);
			
			storesOverlay.addOverlay(poiOverlay);
		}
		mapView.postInvalidate();
		
	}

	

}
